<template>
    <!-- 资质信息 -->
    <div class="e-table">
        <div class="top">
            <div class="left">
                <div>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="aptitudeAddRow"
                    >
                        添加
                    </el-button>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDownload"
                        v-if="isBatch"
                    >
                        批量下载
                    </el-button>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDelete"
                        v-if="isBatch"
                    >
                        批量删除
                    </el-button>
                </div>

                <div class="batchBox" @click="batchOperation">
                    <img class="batchicon" src="@/assets/piliang.png" />
                    <span class="batchfont">{{ batch }}</span>
                </div>
            </div>

            <div class="right" v-if="!isTableRowClass">
                <div class="squarecolor">
                    <div class="color colorAdd"></div>
                    <span>新增</span>
                </div>
                <div class="squarecolor item">
                    <div class="color colorUpdate"></div>
                    <span>修改</span>
                </div>
                <div class="squarecolor">
                    <div class="color colorDel"></div>
                    <span>删除/过期</span>
                </div>
            </div>
        </div>
        <div
            style="margin-bottom: 20px"
            class="errorMsg"
            v-if="errorMsg.length > 0"
        >
            <span
                style="display: block"
                v-for="(item, index) in errorMsg"
                :key="index"
            >
                {{ item }}
            </span>
        </div>
        <el-table
            :data="aptitudeTable"
            border
            style="width: 100%"
            :max-height="$store.state.tableHeight"
            @selection-change="handleDetailSelectionChange"
            @cell-click="cellClick"
            :row-class-name="tableRowClass"
            ref="table"
            class="table"
            v-sortTable="{ 'tableData': aptitudeTable, '_this': this, 'ref': 'table' }"
        >
            <el-table-column
                type="selection"
                width="55"
                v-if="isBatch"
            ></el-table-column>
            <el-table-column label="序号" type="index" width="60">
            </el-table-column>
            <el-table-column fixed label="操作" width="120">
                <template slot-scope="{ row, $index }">
                    <div class="handle">
                        <el-upload
                            style="margin: 7px 5px 0px 0px"
                            class="upload-demo"
                            :action="uploadUrl"
                            :data="{
                                bucketName,
                                relationId,
                                orgCode
                            }"
                            :before-upload="beforeAvatarUpload"
                            :accept="accept"
                            :on-success="attachOnSuccess"
                            :http-request="uploadBefore"
                            :show-file-list="false"
                            name="files"
                        >
                            <img src="@/assets/btn/commit.png" />
                        </el-upload>
                        <img
                            v-if="row.id"
                            src="@/assets/btn/downLoad.png"
                            @click="handleDownload(row)"
                            style="margin-right: 5px"
                        />
                        <img
                            v-if="row.changeType != -1"
                            src="@/assets/btn/delete.png"
                            @click="handleDelete(row, $index)"
                        />
                        <img
                            v-else
                            src="@/assets/btn/cancelDelete.png"
                            @click="revoke($index)"
                        />
                        <img
                            style="margin-left: 10px"
                            src="@/assets/btn/preview.png"
                            @click="preview($index)"
                        />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="证书类型" width="160" show-overflow-tooltip>
                <template slot-scope="{ row, $index }">
                    <el-select
                        v-model="row.certTypeValue"
                        @change="getCertType(row, row.certTypeValue, $index)"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in certType"
                            :key="item.kvId"
                            :label="item.kvKey"
                            :value="item.kvKey"
                        ></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="证书编号" width="180" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    <el-input
                        :readonly="row.isShowcertNo"
                        v-model.trim="row.certNo"
                        @change="modifyState(row)"
                    ></el-input>
                </template>
            </el-table-column>

            <el-table-column
                prop="qualificationLevelName"
                label="主营范围/证书等级"
                width="150"
                show-overflow-tooltip
            >
                <template slot-scope="{ row, $index }">
                    <el-tooltip
                        class="item"
                        effect="dark"
                        :content="row.qualificationLevelName"
                        :disabled="!row.qualificationLevelName"
                        placement="top"
                    >
                        <span>
                            <el-input
                            v-if="row.gradeShow"
                            readonly
                            v-model="row.qualificationLevelName"
                            placeholder="请选择"
                        >
                            <i
                                slot="suffix"
                                class="el-icon-document-copy"
                                @click="onSelect(row, $index)"
                            ></i>
                        </el-input>
                        </span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column
                prop="startDate"
                label="有效期开始日期"
                width="160"
            >
                <template slot-scope="{ row, $index }">
                    <el-date-picker
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        v-model="row.startDate"
                        style="width: 100%"
                        @change="choiceStart(row, $event, $index)"
                    ></el-date-picker>
                </template>
            </el-table-column>
            <el-table-column prop="endDate" label="有效期结束日期" width="260">
                <template slot-scope="{ row, $index }">
                    <div>
                        <el-select
                            v-if="row.isShowSelset"
                            style="width: 100px; margin-right: 5px"
                            v-model="row.isShow"
                            @change="changeDate(row, $index, $event)"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in aptitudeTable[$index]
                                    .endDateStyle"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                        <el-date-picker
                            v-if="row.isShow != '0'"
                            :disabled="row.isShow != '1'"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            v-model="row.endDate"
                            style="width: 130px"
                            @change="modifyState(row)"
                        ></el-date-picker>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                prop="fileName"
                label="资质附件"
                min-width="200"
                show-overflow-tooltip
            >
                <template slot-scope="{ row }">
                    {{ row.fileName }}
                </template>
            </el-table-column>
            <el-table-column
                prop="size"
                label="大小"
                min-width="120"
                show-overflow-tooltip
            >
                <template slot-scope="{ row }">
                    {{ row.size ? bytesToSize(row.size) : '' }}
                </template>
            </el-table-column>
            <el-table-column
                prop="gmtCreate"
                label="上传时间"
                width="120"
            ></el-table-column>
            <el-table-column
                prop="founderName"
                label="上传人"
                width="120"
            ></el-table-column>
        </el-table>
        <!-- <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog> -->
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import ossRequest from '@/api/oss/oss.js'
import { mapMutations } from 'vuex'
import { bytesToSize, showLoading, hideLoading, getUuid } from '@/utils/common'
import { qualificationList } from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractor.js'
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'
import { selectDataClient } from '@/utils/common'
//import ComPagination from '@/components/pagination/pagination'
import service from '@/utils/request'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
export default {
    props: {
        bucketName: {
            type: String,
            default: '',
            require: true
        },
        // 单据id
        billId: {
            type: String,
            default: '',
            require: true
        },
        outerNames: {
            type: String,
            default: '',
            require: true
        },
        aptitudeTables: {
            type: Array,
            require: true
        },
        fun: {
            type: Function,
            default: null
        },
        // 是否需要修改样式
        isTableRowClass: {
            type: Boolean,
            default: false
        },
        // 分包商类型
        subcontractorTypeValue: {
            type: Array,
            default: () => {
                return []
            }
        },
        // 是否为境外单位
        isAbroadUnit: {
            type: [String, Number],
            default: ''
        },
        // 统一社会信用代码
        creditCodeSon: {
            type: String,
            default: ''
        },
        // 是否通过验证
        aptitudeSend: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            isBatch: false, //是否进入批量操作
            batch: '进入批量管理',
            aptitudeTable: [], //资质信息表格数据
            checkedDetail: [], //选中的数据
            //上传的地址
            uploadUrl: 'oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            relationId: '',
            pagination: {
                limit: 10, //	每页显示条数
                name: '', //合同名称
                orgName: '', //机构
                page: 1 //当前页数
            },
            totalPage: 0, //总页数
            rowIndex: '',
            certType: [],
            unWatch: '',
            errorMsg: [], //验证数组
            isShowcertNo: false, //是否禁用证书编号
            deleteDate: {}, //删除对象
            oldDate: [], //列表查回来的基础数据
            // dialogVisible: false, //弹窗开关
            // dialogImageUrl: '' //回显路径
        }
    },
    async created () {
        showLoading()
        // await this.findByIdqualification()
        hideLoading()
        //获取证书类型
        call.getCredential('证书类型').then(res => {
            this.certType = res
        })
        this.qualificationList(this.billId) //初始化资质信息列表
    },
    mounted () {},
    computed: {
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    methods: {
        //修改行样式
        tableRowClass ({ row }) {
            if (this.isTableRowClass) {
                return
            } else {
                if (row.state == -1) {
                    return 'red'
                } else if (row.state == 1) {
                    return 'green'
                } else if (row.state == 2) {
                    return 'yellow'
                }
                return ''
            }
        },
        //选择证书类型的事件
        /**
         * 6)证书类型是营业执照的时候，必须选择主营范围，弹出多选，可选择除了第一级的任意一级；
         * 7)证书类型是资质证书的时候，必须选择资质等级，弹出多选，可选择除了第一级的任意一级；
         * 8)证书类型没有选择或不是资质证书和营业执照时的时候，主营范围/资质等级禁用；
         */
        // eslint-disable-next-line no-unused-vars
        getCertType (row, certTypeValue, $index) {
            this.modifyState(row)
            this.aptitudeTable[$index].endDateStyle = [
                { name: '时间格式', id: '1' }
            ]

            let number = 0
            // 判断证书类型是否已经选择
            this.aptitudeTable.map(item => {
                if (item.certTypeValue == certTypeValue) {
                    number += 1
                    return
                }
            })
            if (number > 1) {
                this.errorMsg.push(certTypeValue + '已经存在')
            }
            /**
           * a.营业执照：可选择永久和日期选择器；
            b.资质证书：只能通过日期选择器选择日期；
            c.安全生产许可证：不能选择日期选择器，根据有效期开始日期，结束日期自动加3年；
           */
            if (certTypeValue == '营业执照') {
                this.aptitudeTable[$index].isShowSelset = true
                // 当选择为营业执照时，默认赋值为统一社会信用代码，并且不能修改
                this.aptitudeTable[$index].certNo = this.creditCodeSon
                this.aptitudeTable[$index].isShowcertNo = true
                this.aptitudeTable[$index].isShow = '1'
                this.aptitudeTable[$index].endDateStyle.push({
                    name: '永久',
                    id: '0'
                })
                // 弹窗按钮显示
                this.aptitudeTable[$index].gradeShow = true
            }
            if (certTypeValue == '资质证书') {
                this.aptitudeTable[$index].certNo = ''
                this.aptitudeTable[$index].isShowcertNo = false
                this.aptitudeTable[$index].isShowSelset = true
                this.aptitudeTable[$index].isShow = '1'
                // 弹窗按钮显示
                this.aptitudeTable[$index].gradeShow = true
            }
            if (certTypeValue == '安全生产许可证') {
                this.aptitudeTable[$index].certNo = ''
                this.aptitudeTable[$index].isShowcertNo = false
                this.aptitudeTable[$index].isShowSelset = false
                this.aptitudeTable[$index].isShow = '2'
                this.aptitudeTable[$index].gradeShow = false
            }
            if (certTypeValue == '其它') {
                this.aptitudeTable[$index].isShowcertNo = false
                this.aptitudeTable[$index].gradeShow = false
            }
        },
        ...mapMutations(['setSelectedInfo']),
        // 弹窗
        onSelect (value, index) {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/config/kv/getDicValueTree', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    dicName:
                        value.certTypeValue == '营业执照'
                            ? '外包方主营范围'
                            : '资质等级',
                    parentId: '0'
                }),
                Title:
                    value.certTypeValue == '营业执照'
                        ? '请选择主营范围'
                        : '请选择资质等级' // 标题
            }).then(val => {
                // 定义空数组，存选中的name
                let newclassName = []
                let newbillId = []
                val.map(item => {
                    newclassName.push(item.kvValue)
                    newbillId.push(item.kvId)
                })
                this.aptitudeTable[index].qualificationLevelId = newbillId.join(',')
                this.aptitudeTable[index].qualificationLevelName =
                    newclassName.join(',')
            })
        },
        //是否批量管理
        batchOperation () {
            this.isBatch = !this.isBatch
            if (this.isBatch) {
                this.batch = '退出批量管理'
                this.$refs.table.clearSelection()
            } else {
                this.batch = '进入批量管理'
            }
        },
        cellClick (row) {
            //是第几行
            this.rowIndex = this.aptitudeTable.findIndex(x => x === row)
        },
        //资质信息添加一行
        aptitudeAddRow () {
            let obj = {
                certNo: '', //证书编号
                certTypeKey: '', //	证书类型（字典）
                certTypeValue: '', //证书类型（字典）
                changeType: 1, //前端操作状态
                endDate: '', //结束日期
                fileName: '', //文件名
                founderId: '', //文件下载路经
                founderName: '', //文件大小
                gmtCreate: '', //上传人
                gmtModified: '', //	上传人
                id: '', //录入人Id
                outerBillId: this.billId, //外包方id
                outerName: this.outerNames, //外包方名字
                outerTypeKey: '', //明细Id
                outerTypeValue: '', //外包方Id
                qualificationLevelId: '', //资质等级id
                qualificationLevelName: '', //资质等级名称
                relationId: '', //关联ID
                startDate: '', //开始日期
                isShow: '1', //是否展示时间组件
                isShowcertNo: false, //是否禁用证书编号
                endDateStyle: [{ name: '时间格式', id: '1' }], //选择时间的数据
                isShowSelset: true, //是否展示选择时间选择组件
                uuid: getUuid(), //本地的uuid区分每条数据
                state: 1,
                newState: '1', //当期新增字段，判断是当前次新增的数据还是从后端请求回来的数据
                gradeShow: false, //弹窗按钮显示与否
            }
            this.aptitudeTable.push(obj)
        },
        //选中的行
        handleDetailSelectionChange (selection) {
            this.checkedDetail = selection
        },
        //删除一行
        handleDelete (row, $index) {
            if (this.isTableRowClass) {
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    this.callback(row, $index)
                )
            } else {
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    this.callbacks(row, $index)
                )
            }
        },
        // 编辑删除回调
        callback (row, index) {
            return () => {
                if (row.id) {
                    let data = []
                    row.changeType = -1
                    // 判断是否是原单数据，【只有变更数据才会有原单id】
                    if (row.sourceId) {
                        row.state = -1
                    }
                    data.push(row)
                    this.$emit('getAptitudeData', data)
                } else {
                    this.aptitudeTable.splice(index, 1)
                }
            }
        },
        // 变更删除回调
        callbacks (row, index) {
            return () => {
                if (!row.newState) {
                    this.aptitudeTable[index].changeType = -1
                    this.aptitudeTable[index].state = -1
                } else {
                    this.aptitudeTable.splice(index, 1)
                }
            }
        },
        // 撤销
        revoke (index) {
            this.aptitudeTable[index].changeType = 0
            this.aptitudeTable[index].state = 1
        },

        //批量删除
        handleBatchDelete () {
            const length = this.checkedDetail.length
            this.clientPop('info', this.moreDeleteErr(length), this.delete)
        },
        delete () {
            this.checkedDetail.filter(item => {
                // 如果有id ，则改changeType为-1
                if (item.id) {
                    item.changeType = -1
                } else {
                    // 如果没有id，判断uuid是否相同，相同则在原数据删除
                    this.aptitudeTable.map((items, index) => {
                        if (item.uuid == items.uuid) {
                            this.aptitudeTable.splice(index, 1)
                        }
                    })
                }
            })
            // 直接过滤所有无id的数据
            let data = this.checkedDetail.filter(item => {
                if (item.id) {
                    return item
                }
            })
            this.$emit('getAptitudeData', data)
        },
        //批量下载
        handleBatchDownload () {},
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    res.map(x => {
                        x.fileName = x.objectName
                        x.size = x.objectSize
                        x.founderName = x.ossBucketName
                        return scrollX
                    })
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'dialogImage',
                        res[0].objectPath
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'fileName',
                        res[0].objectName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'size',
                        res[0].objectSize
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'founderName',
                        res[0].ossBucketName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'relationId',
                        this.relationId
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'gmtCreate',
                        res[0].gmtCreate.slice(0, res[0].gmtCreate.indexOf(' '))
                    )
                    // })
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'fileName',
                        res[0].objectName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'size',
                        res[0].objectSize
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'founderName',
                        res[0].ossBucketName
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'relationId',
                        this.relationId
                    )
                    this.$set(
                        this.aptitudeTable[this.rowIndex],
                        'gmtCreate',
                        res[0].gmtCreate.slice(0, res[0].gmtCreate.indexOf(' '))
                    )
                    // 上传成功调用变色方法
                    this.modifyState(this.aptitudeTable[this.rowIndex])
                })
        },
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //保存
        preserve () {
            this.errorMsg = []
            // 首先将changeTy为-1的过滤掉
            let data = this.aptitudeTable.filter(item => {
                return item.changeType != -1
            })
            // 验证是否有数据
            let isStr = false
            data.forEach((item, index) => {
                let str1 = `请完善第 ${index + 1} 行的`
                if (item.certTypeValue === '' || item.certTypeValue === null) {
                    let str = '证书类型,'
                    isStr = true
                    str1 += str
                }
                if (item.startDate === '' || item.startDate === null) {
                    let str = '开始时间,'
                    isStr = true
                    str1 += str
                }
                if (item.endDate === '' || item.endDate === null) {
                    let str = '结束时间,'
                    isStr = true
                    str1 += str
                }
                if (item.fileName === '' || item.fileName === null) {
                    let str = '资质附件,'
                    isStr = true
                    str1 += str
                }
                if(item.certTypeValue == '营业执照' || item.certTypeValue == '资质证书') {
                    if (item.qualificationLevelName === '' || item.qualificationLevelName === null) {
                        let str = '主营范围/证书等级,'
                        isStr = true
                        str1 += str
                    }
                }
                if (Date.parse(item.startDate) >= Date.parse(item.endDate)) {
                    let str = '结束时间必须大于开始时间,'
                    isStr = true
                    str1 += str
                }
                if (item.certNo === '' || item.certNo === null) {
                    let str = '证书编号,'
                    isStr = true
                    str1 += str
                }
                if (isStr) {
                    this.errorMsg.push(str1)
                }
            })
            if (this.errorMsg.length > 0) {
                this.$emit('update:aptitudeSend', false)
                this.$emit('setError', 'aptitude')
                return
            } else {
                if (data.length > 0) {
                    // 调用保存方法
                    this.qualificationAdd(data)
                } else {
                    this.$emit('update:aptitudeSend', false)
                    this.errorMsg.push('请添加资质信息')
                    this.$emit('setError', 'aptitude')
                }
            }
        },
        // 资质信息列表
        async qualificationList (val) {
            // 如果有isTableRowClass，则调编辑页面的资质接口，否则调变更页面的资质接口
            let data = []
            if (this.isTableRowClass) {
                data = await qualificationList(val)
            } else {
                data = await subcontractorChange.findByIdqualification(val)
                // 将该值赋值保存
            }
            // 如果有数据。则赋值给列表数据
            if (data.length > 0) {
                // 处理有效结束时间的回显
                this.aptitudeTable = data.map(item => {
                    if (new Date(item.endDate).getFullYear() == 9999) {
                        item.isShow = '0'
                        item.isShowcertNo = true
                        if (!item.endDateStyle) {
                            item.endDateStyle = [
                                {
                                    name: '永久',
                                    id: '0'
                                },
                                {
                                    name: '时间格式',
                                    id: '1'
                                }
                            ]
                        }
                        item.isShowSelset =
                            item.certTypeValue !== '安全生产许可证'
                    } else if (item.certTypeValue === '安全生产许可证') {
                        item.isShow = '2'
                    } else {
                        item.isShow = '1'
                    }
                    // 判断哪些显示供应商品
                    if (
                        item.certTypeValue == '营业执照' ||
                        item.certTypeValue == '资质证书'
                    ) {
                        item.gradeShow = true
                    }
                    return item
                })
                this.oldDate = JSON.parse(JSON.stringify(this.aptitudeTable))
            }
        },
        //分包商资质信息新增(修改)
        async qualificationAdd (val) {
            let isContain = [] //定义证书类型临时数组
            // 将证书类型存入临时数组
            isContain = val.map(item => {
                if (item.state != -1) {
                    return item.certTypeValue
                }
            })
            // 判断哪些字段重复
            var result = [] //不重复字段
            var result2 = [] //重复字段
            for (var i = 0; i < isContain.length; i++) {
                if (result.indexOf(isContain[i]) == -1) {
                    result.push(isContain[i])
                } else {
                    if (result2.indexOf(isContain[i]) == -1) {
                        result2.push(isContain[i])
                    }
                }
            }
            // 判断是否重复，如果重复不进行下一步判断
            if (result2.length < 1) {
                // 判断数据是否完整并且符合条件
                /**
                 * 1.分包商类型选择“劳务合作、施工分包”中的1个或2个，且不是境外单位的时候，必须上传营业执照、资质证书和安全生产许可证；
                 * 2.勾选了境外单位或外包方类型只有其它的时候，则必须上传营业执照
                 */
                let newData = this.subcontractorTypeValue.join(',')
                if (newData == '10' || this.isAbroadUnit == 1) {
                    //判断证书类型是否包含营业执照，不包含则提示
                    if (isContain.includes('营业执照')) {
                        // 将值传回父组件
                        val.map(item => {
                            if (item.id) {
                                item.changeType = 2
                                return item
                            }
                        })
                        this.$emit('update:aptitudeSend', true)
                        this.$emit('update:aptitudeTables', val)
                    } else {
                        this.errorMsg.push('资质信息必须包含:营业执照,请检查')
                        this.$emit('update:aptitudeSend', false)
                        this.$emit('setError', 'aptitude')
                    }
                } else {
                    // 如果列表数据不足3条则直接提示不符合条件
                    //判断证书类型是否包含三种类型，不包含则提示
                    if (
                        isContain.includes('营业执照') &&
                        isContain.includes('资质证书') &&
                        isContain.includes('安全生产许可证')
                    ) {
                        val.map(item => {
                            if (item.id) {
                                item.changeType = 2
                                return item
                            }
                        })
                        // 将值传回父组件
                        this.$emit('update:aptitudeSend', true)
                        this.$emit('update:aptitudeTables', val)
                    } else {
                        let str = []
                        if (!isContain.includes('营业执照')) {
                            str.push('营业执照')
                        }
                        if (!isContain.includes('资质证书')) {
                            str.push('资质证书')
                        }
                        if (!isContain.includes('安全生产许可证')) {
                            str.push('安全生产许可证')
                        }
                        this.errorMsg.push(`资质信息必须包含:${str},请检查`)
                        this.$emit('update:aptitudeSend', false)
                        this.$emit('setError', 'aptitude')
                    }
                }
            } else {
                result2.map(item => {
                    this.errorMsg.push(`${item}'重复'`)
                })
            }
        },
        // 获取用户选择的是否是永久，
        changeDate (row, index, val) {
            this.modifyState(row)
            if (val == 0) {
                this.aptitudeTable[index].endDate = '9999-12-30'
            } else {
                this.aptitudeTable[index].endDate = new Date()
            }
        },
        //选择开始时间触发事件
        choiceStart (row, value, index) {
            this.modifyState(row)
            if (row.certTypeValue == '安全生产许可证') {
                let tempTime1 = Date.parse(value)
                let newDate = tempTime1 + 31536000000 * 3
                let time = new Date(newDate)
                let year = time.getFullYear() //年
                let month = ('0' + (time.getMonth() + 1)).slice(-2) //月
                let day = ('0' + time.getDate()).slice(-2) //日
                let mydate = year + '-' + month + '-' + day
                this.aptitudeTable[index].endDate = mydate
            }
        },
        // 修改样式
        modifyState (row) {
            this.oldDate.map(item => {
                if (item.id == row.id && row.relationId) {
                    // if( !this.isObjectValueEqual(item, row)) {
                    this.aptitudeTable.map(items => {
                        if (items.id == row.id) {
                            return (items.state = 2)
                        }
                    })
                    // }
                }
            })
        },
        //预览附件
        preview (val) {
            if (this.aptitudeTable[val].dialogImage) {
                window.open(this.aptitudeTable[val].dialogImage)
            } else {
                this.clientPop('err', '请先上传附件')
            }
        },
        //下载某一行
        async handleDownload (obj) {
            showLoading()
            const url = obj.dialogImage
            const fileNameFull = obj.fileName
            const fileExt = fileNameFull.split('.').pop()
            if (
                ['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(
                    fileExt.toLowerCase()
                ) === -1
            ) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
            hideLoading()
        },
        downloadIamge (imgsrc, fileName) {
        //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {
                // if browser is IE
                    navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        }
    },

}
</script>

<style lang="scss" scoped>
.handle {
    display: flex;
    align-items: center;
    text-align: left;
    div {
        cursor: pointer;
    }
    .download {
        font-size: 23px;
        font-weight: bold;
        color: rgb(122, 168, 24);
    }
}
</style>
